package com.example.lesson2;

import java.util.concurrent.TimeUnit;

import com.example.pages.InternalPage;
import com.example.pages.LoginPage;
import com.example.pages.UserManagementPage;
import org.junit.*;
import static org.junit.Assert.*;

import org.openqa.selenium.*;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.PageFactory;
import ru.esteru.selenium.factory.WebDriverFactory;

public class TC004DeleteUser {
    private static WebDriver driver;
    private static String baseUrl;
    private static StringBuffer verificationErrors = new StringBuffer();
    private LoginPage loginPage;
    private InternalPage internalPage;
    private UserManagementPage userManagementPage;

    @Before
    public void setUp() throws Exception {
        driver = WebDriverFactory.getDriver(DesiredCapabilities.firefox());
        baseUrl = "http://localhost/";
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    }

    @Test
    public void DeleteUser() throws Exception{
        goToMainPage();
        loginAs("admin", "admin");
        goToUserManagementPage();
        deleteUser();
        //Assert.assertEquals(2, driver.findElements(By.xpath("//div[@class = 'content']/table//tbody/tr")).size());
        Assert.assertEquals(1, userManagementPage.getTotalUsersNumberInTable(driver).size());
        logout();
    }

     private void deleteUser() {
        userManagementPage.findUserToDelete.click();
        driver.switchTo().alert().accept();
    }

    private void goToUserManagementPage() {
        internalPage.menuUserManagementLink.click();
    }

    private void logout() {
        internalPage.menuLogoutLink.click();
        driver.switchTo().alert().accept();
//        driver.quit();
    }

    private void loginAs(String username, String password) {
        loginPage.userNameField.clear();
        loginPage.userNameField.sendKeys(username);
        loginPage.passwordField.clear();
        loginPage.passwordField.sendKeys(password);
        loginPage.loginButton.click();
    }

    private void goToMainPage() {
        driver.get(baseUrl + "/php4dvd/");
        loginPage = PageFactory.initElements(driver, LoginPage.class);
        internalPage = PageFactory.initElements(driver, InternalPage.class);
        userManagementPage = PageFactory.initElements(driver, UserManagementPage.class);
    }

    @After
    public void tearDown() throws Exception {
        String verificationErrorString = verificationErrors.toString();
        if (!"".equals(verificationErrorString)) {
            fail(verificationErrorString);
        }
    }

    private boolean isElementPresent(By by) {
        try {
            driver.findElement(by);
            return true;
        } catch (NoSuchElementException e) {
            return false;
        }
    }
}
